<?php
// +----------------------------------------------------------------------
// | JSHOP [ 小程序商城 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://jihainet.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: mark <jima@jihainet.com>
// +----------------------------------------------------------------------

namespace app\common\model;

use think\Db;


/**
 * 蒙版类型
 * Class GoodsType
 * @package app\common\model
 * User: wjima
 * Email:1457529125@qq.com
 * Date: 2018-01-09 20:09
 */
class Banxing extends Common
{

//    use SoftDelete;
//    protected $deleteTime = 'isdel';
    protected $autoWriteTimestamp = true;
    protected $createTime = 'ctime';
    protected $updateTime = 'utime';

    const MARKETABLE_UP = 1; //上架
    const MARKETABLE_DOWN = 2;//下架

    public function tableData($post, $isPage = true)
    {
        if (isset($post['limit'])) {
            $limit = $post['limit'];
        } else {
            $limit = config('paginate.list_rows');
        }
        $tableWhere = $this->tableWhere($post);
        $query = $this
            ->field($tableWhere['field'])->where($tableWhere['where'])->whereOr($tableWhere['whereOr'])->order($tableWhere['order']);

        if ($isPage) {
            $list = $query->paginate($limit);
            $data = $this->tableFormat($list->getCollection());         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型
            $re['count'] = $list->total();
        } else {
            $list = $query->select();
            $data = $this->tableFormat($list);         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型
            $re['count'] = count($list);
        }

        $re['code'] = 0;
        $re['msg'] = '';
        $re['data'] = $data;
        return $re;
    }

    /**
     * 默认排序
     * @param $post
     * @return mixed
     * User: wjima
     * Email:1457529125@qq.com
     * Date: 2018-01-11 16:32
     */
    protected function tableWhere($post)
    {
        $where = $whereOr = [];
        if (isset($post['marketable']) && $post['marketable'] != "") {
            $where[] = ['marketable', 'eq', $post['marketable']];
        }
        if (isset($post['name']) && $post['name'] != "") {
            $where[] = ['name', 'like', '%' . $post['name'] . '%'];
        }
        if (isset($post['id']) && $post['id'] != "") {
            $where[] = ['id', 'in', $post['id']];
        }
        if (isset($post['warn']) && $post['warn'] == "true") {
            $SettingModel = new Setting();
            $goods_stocks_warn = $SettingModel->getValue('goods_stocks_warn');
            $goods_stocks_warn = $goods_stocks_warn ? $goods_stocks_warn : '10';
            $productModel = new Products();
            $baseFilter[] = ['(stock - freeze_stock)', 'lt', $goods_stocks_warn];
            $goodsIds = $productModel->field('goods_id')->where($baseFilter)->group('goods_id')->select();
            if (!$goodsIds->isEmpty()) {
                $goodsIds = array_column($goodsIds->toArray(), 'goods_id');
                $where[] = ['id', 'in', $goodsIds];
            } else {
                $where[] = ['id', 'in', 0];
            }
        }
        if (isset($post['goods_type_id']) && $post['goods_type_id'] != "") {
            $where[] = ['goods_type_id', 'eq', $post['goods_type_id']];
        }
        if (isset($post['brand_id']) && $post['brand_id'] != "") {
            $where[] = ['brand_id', 'eq', $post['brand_id']];
        }
        if (isset($post['bn']) && $post['bn'] != "") {
            $where[] = ['bn', 'like', '%' . $post['bn'] . '%'];
        }

        if (isset($post['last_cat_id']) && $post['last_cat_id'] != "") {
            $where[] = ['goods_cat_id', 'eq', $post['last_cat_id']];
        }

        if (isset($post['goods_cat_id']) && $post['goods_cat_id'] != "" && !$post['last_cat_id']) {

            if ($post['goods_cat_id']) {
                $goodsCatModel = new GoodsCat();
                $catIds = [];
                $childCats = $goodsCatModel->field('id')->where(['parent_id' => $post['goods_cat_id']])->select();
                if (!$childCats->isEmpty()) {
                    $catIds = array_column($childCats->toArray(), 'id');
                }
                $catIds[] = $post['goods_cat_id'];
                $whereOr[] = ['goods_cat_id', 'in', $catIds];
            }
        }

        $result['where'] = $where;
        $result['whereOr'] = $whereOr;

        $result['field'] = "*";
        $result['order'] = ['id' => 'desc'];
        return $result;
    }

    /**
     * 保存蒙版
     * User:wjima
     * Email:1457529125@qq.com
     * @param array $data
     * @return mixed
     */
    public function doAdd($data = [])
    {
        $result = $this->insert($data);
        if ($result) {
            return $this->getLastInsID();
        }
        return $result;
    }

    protected function tableFormat($list)
    {

        foreach ($list as $key => $val) {
            $list[$key]['image'] = _sImage($val['image_id']);
            $list[$key]['cate_id'] = _sCate($val['cate_id']);
        }
        return $list;
    }


    /**
     * 更新蒙版信息
     * @param       $goods_id
     * @param array $data
     * @return false|int
     * User: wjima
     * Email:1457529125@qq.com
     * Date: 2018-01-23 19:37
     */
    public function updateGoods($goods_id, $data = [])
    {
        return $this->save($data, ['id' => $goods_id]);
    }

    /**
     * 获取商品分类列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getList()
    {

        $data = $this->field('id, cate_id, name, sort, image_id')
            ->order(['sort' => 'asc'])
            ->select();

        $return_data = $this->getTree($data);
        return $return_data;
    }


    /**
     * 转换成树状
     * @param $data
     * @return array
     */
    protected function getTree($data)
    {

        $new_data = array();
        foreach ($data as &$v) {
            if (!isset($new_data[$v['cate_id']]['name'])) {
                $new_data[$v['cate_id']]['name'] = model('Common/GoodsCat')->getCatInfo($v['cate_id'])['name'];
                $new_data[$v['cate_id']]['child'] = [];
            }
            array_push($new_data[$v['cate_id']]['child'], $v->toArray());

        }

        $return_data = array();

        foreach ($new_data as $key=>$v) {
            $return_data[] = array(
                'id' => $v['id'],
                'name_1' => $v['name'],
                'name_2' => '',
                'image_id' => $this->getImage($v['image_id']),
                'sort' => $v['sort'],
            );

            foreach ($v['child'] as $vv) {

                $data = array(
                    'id' => $vv['id'],
                    'name_1' => '',
                    'name_2' => $vv['name'],
                    'image_id' => $this->getImage($vv['image_id']),
                    'sort' => $vv['sort'],
                    'operating' =>$this->getOperating($vv['id']),
                );
                array_push($return_data,$data);
            }
        }

        return $return_data;
    }


    /**
     * 生成操作按钮
     * @param $id
     * @param int $type
     * @return string
     */
    protected function getOperating($id)
    {
        $html = '';

        $html .= '<a class="layui-btn layui-btn-xs edit-class" data-id="' . $id . '">编辑</a>';
        $html .= '<a class="layui-btn layui-btn-danger layui-btn-xs del-class" data-id="' . $id . '">删除</a>';
        return $html;
    }


    /**
     * 获取图片
     * @param $image_id
     * @return string
     */
    protected function getImage($image_id)
    {
        if ($image_id) {
            return _sImage($image_id);
        } else {
            return '';
        }
    }


    /**
     * 获取goods表图片对应图片地址
     * @return $this
     * User: wjima
     * Email:1457529125@qq.com
     * Date: 2018-01-29 16:26
     */
    public function defaultImage()
    {
        return $this->hasOne('Images', 'id', 'image_id')->field('id,url')->bind(['image_url' => 'url']);
    }


    /**
     * 获取分类名称
     * @return $this
     * User: wjima
     * Email:1457529125@qq.com
     * Date: 2018-01-31 11:46
     */
    public function goodsCat()
    {
        return $this->hasOne('GoodsCat', 'id', 'goods_cat_id')->field('id,name')->bind(['cat_name' => 'name']);
    }


    /*
     * 无数据转换
     * */
    public function getOne($goods_id, $fields = '*')
    {
        $result = [
            'status' => false,
            'data' => [],
            'msg' => '蒙版不存在'
        ];
        $data = $this->where(['id' => $goods_id])->field($fields)->find();
        if ($data) {
            $goodsImagesModel = new goodsImages();
            $images = $goodsImagesModel->getAllImages($data->id);
            $tmp_image = [];
            if ($images['status']) {
                foreach ((array)$images['data'] as $key => $val) {
                    $images['data'][$key]['image_path'] = _sImage($val['image_id']);
                }
                $tmp_image[] = [
                    'goods_id' => $data['id'],
                    'image_id' => $data['image_id'],
                    'image_path' => _sImage($data['image_id']),
                ];
                $images['data'] = array_merge((array)$images['data'], (array)$tmp_image);
                $images['data'] = array_reverse($images['data']);
            } else {
                //单图
                $tmp_image[] = [
                    'goods_id' => $data['id'],
                    'image_id' => $data['image_id'],
                    'image_path' => _sImage($data['image_id']),
                ];
                $images['data'] = $tmp_image;
            }
            $data['products'] = $this->products($goods_id, false);

            $data['images'] = $images['data'];
            $result['data'] = $data;
            $result['msg'] = '查询成功';
            $result['status'] = true;
        }
        return $result;
    }


    /**
     * 删除蒙版
     * @param int $goods_id
     * @return array
     */
    public function delGoods($goods_id = 0)
    {
        $result = [
            'status' => false,
            'data' => [],
            'msg' => '蒙版不存在'
        ];
        $goods = $this::get($goods_id);
        if (!$goods) {
            return $result;
        }

        $this->startTrans();

        $res = self::destroy($goods_id);
        if (!$res) {
            $this->rollback();
            $result['msg'] = '蒙版删除失败';
            return $result;
        }
        $productsModel = new Products();
        $delProduct = $productsModel->where(['goods_id' => $goods_id])->delete(true);
        if (!$delProduct) {
            $this->rollback();
            $result['msg'] = '货品删除失败';
            return $result;
        }
        //删除关联图片
        $goodsImagesModel = new GoodsImages();
        $delImages = $goodsImagesModel->delImages($goods_id);
        if (!$delImages['status']) {
            $this->rollback();
            $result['msg'] = '图片删除失败';
            return $result;
        }
        delImage($goods['image_id']);
        $this->commit();

        hook('deletegoodsafter', $goods);//删除蒙版后增加钩子

        $result['status'] = true;
        $result['msg'] = '删除成功';
        return $result;
    }

    /**
     * 批量上下架
     * @param $ids
     * @param string $type
     * @return static
     */
    public function batchMarketable($ids, $type = 'up')
    {

        if ($type == 'up') {
            $marketable = self::MARKETABLE_UP;
        } elseif ($type == 'down') {
            $marketable = self::MARKETABLE_DOWN;
        }
        $data = [
            'marketable' => $marketable,
            $type . 'time' => time(),
        ];
        return $this::where('id', 'in', $ids)->update($data);
    }


    /**
     * 添加蒙版
     * @param $data
     * @return int|string
     */
    public function add($data)
    {
        return $this->insert($data);
    }


    /**
     * 编辑蒙版
     * @param $data
     * @return int|string
     */
    public function edit($data)
    {
        $return = [
            'status' => false,
            'msg' => '',
            'data' => []
        ];

        $res = $this->update($data);
        $return['data'] = $res;
        if ($res) {
            $return['status'] = true;
            $return['msg'] = '修改成功';
        } else {
            $return['msg'] = '修改失败';
        }
        return $return;
    }


    /**
     * 删除蒙版
     * @param int $goods_id
     * @return array
     */
    public function delLayermask($id = 0)
    {
        $result = [
            'status' => false,
            'data' => [],
            'msg' => '商品不存在'
        ];
        $layermask = $this::get($id);
        if (!$layermask) {
            return $result;
        }
        $this->startTrans();
        $res = self::destroy($id);
        if (!$res) {
            $this->rollback();
            $result['msg'] = '蒙版删除失败';
            return $result;
        }
        $this->commit();

        $result['status'] = true;
        $result['msg'] = '删除成功';
        return $result;
    }

}